<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="提醒：只允许选择第三级分类设置分类参数！" type="warning" :closable="false" show-icon></el-alert>
            <el-row class="cate-opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader
                        v-model="cateSelectValues"
                        :options="cateList"
                        :props="cateProps"
                        @change="cateChange"
                    ></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="tabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button
                        type="primary"
                        size="mini"
                        :disabled="isBtnDisabled"
                        @click="openParamsDialog"
                    >添加参数</el-button>
                    <el-table :data="manyTableData" border stripe style="width: 100%">
                        <el-table-column type="expand">
                            <template v-slot="scope">
                                <el-tag
                                    v-for="(item, index) in scope.row.attr_vals"
                                    :key="index"
                                    closable
                                    @close="deleteAttr(scope.row, index)"
                                >{{ item }}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                ></el-input>
                                <el-button
                                    v-else
                                    class="button-new-tag"
                                    size="small"
                                    @click="showInput(scope.row)"
                                >+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="序号" width="60"></el-table-column>
                        <el-table-column prop="attr_name" label="分类参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button
                                    type="primary"
                                    size="mini"
                                    icon="el-icon-edit"
                                    @click="openParamsDialog(scope.row)"
                                >编辑</el-button>
                                <el-button
                                    type="danger"
                                    size="mini"
                                    icon="el-icon-delete"
                                    @click="deleteParams(scope.row)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button
                        type="primary"
                        size="mini"
                        :disabled="isBtnDisabled"
                        @click="openParamsDialog"
                    >添加属性</el-button>
                    <el-table :data="onlyTableData" border stripe style="width: 100%">
                        <el-table-column type="expand">
                            <template v-slot="scope">
                                <el-tag
                                    v-for="(item, index) in scope.row.attr_vals"
                                    :key="index"
                                    closable
                                    @close="deleteAttr(scope.row, index)"
                                >{{ item }}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                ></el-input>
                                <el-button
                                    v-else
                                    class="button-new-tag"
                                    size="small"
                                    @click="showInput(scope.row)"
                                >+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="序号" width="60"></el-table-column>
                        <el-table-column prop="attr_name" label="分类属性名称"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button
                                    type="primary"
                                    size="mini"
                                    icon="el-icon-edit"
                                    @click="openParamsDialog(scope.row)"
                                >编辑</el-button>
                                <el-button
                                    type="danger"
                                    size="mini"
                                    icon="el-icon-delete"
                                    @click="deleteParams(scope.row)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加参数/属性窗口 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="paramsDialogVisible"
            width="50%"
            @close="paramsDialogClose"
        >
            <el-form
                :model="paramsForm"
                :rules="paramsFormRules"
                ref="paramsFormRef"
                label-width="100px"
            >
                <el-form-item label="参数名称" prop="attr_name">
                    <el-input v-model="paramsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="paramsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            cateList: [],
            cateSelectValues: [],
            cateProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            activeName: 'many',
            manyTableData: [],
            onlyTableData: [],
            paramsDialogVisible: false,
            paramsForm: {
                attr_id: 0,
                attr_name: ''
            },
            paramsFormRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        // 分类数据列表
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.cateList = res.data
        },
        // cascader选择项
        cateChange() {
            this.getParamsData()
        },
        // tabs切换
        tabClick() {
            this.getParamsData()
        },
        // 参数数据列表
        async getParamsData() {
            if (this.cateSelectValues.length !== 3) {
                this.cateSelectValues = []
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                params: { sel: this.activeName }
            })
            if (res.meta.status !== 200) this.$message.error(res.meta.msg)
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(' ') : []
                item.inputVisible = false
                item.inputValue = ''
            })
            if (this.activeName === 'many') {
                this.manyTableData = res.data
            } else {
                this.onlyTableData = res.data
            }
        },
        // 打开/编辑分类参数窗口
        async openParamsDialog(paramsInfo) {
            if (paramsInfo.attr_id > 0) {
                const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${paramsInfo.attr_id}`, {
                    attr_sel: this.activeName
                })
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.paramsForm = res.data
            }
            this.paramsDialogVisible = true
        },
        // 关闭分类参数窗口
        paramsDialogClose() {
            this.paramsForm.attr_id = 0
            this.$refs.paramsFormRef.resetFields()
        },
        // 保存分类参数
        saveParams() {
            this.$refs.paramsFormRef.validate(async valid => {
                if (!valid) return
                // 修改分类参数
                if (this.paramsForm.attr_id > 0) {
                    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.paramsForm.attr_id}`, {
                        attr_name: this.paramsForm.attr_name,
                        attr_sel: this.activeName
                    })
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                } else {    // 添加分类参数
                    const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                        attr_name: this.paramsForm.attr_name,
                        attr_sel: this.activeName,
                    })
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                }
                this.getParamsData()
                this.paramsDialogVisible = false
            })
        },
        // 删除分类参数
        async deleteParams(paramsInfo) {
            const confirmRes = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                type: 'warning'
            }).catch(err => err)
            if (confirmRes !== 'confirm') return this.$message.info('取消了删除')
            const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${paramsInfo.attr_id}`)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getParamsData()
        },
        // 分类参数行显示新增input
        showInput(row) {
            row.inputVisible = true
            // $nextTick方法作用：当页面上的元素被重新渲染后，才会执行回调函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 分类参数行新增input事件
        handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputVisible = false
                row.inputValue = ''
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputVisible = false
            row.inputValue = ''
            this.saveAttr(row)
        },
        // 删除分类参数项
        deleteAttr(row, i) {
            row.attr_vals.splice(i, 1)
            this.saveAttr(row)
        },
        // 保存分类参数项
        async saveAttr(row) {
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
        }
    },
    computed: {
        // 计算添加参数/属性按钮是否激活状态
        isBtnDisabled() {
            if (this.cateSelectValues.length !== 3) {
                return true
            }
            return false
        },
        // 计算cateId
        cateId() {
            if (this.cateSelectValues.length === 3) {
                return this.cateSelectValues[2]
            }
            return null
        },
        // 计算返回打开/编辑分类参数窗口标题
        dialogTitle() {
            if (this.activeName === 'many') {
                if (this.paramsForm.attr_id > 0) {
                    return "修改动态参数"
                } else {
                    return "添加动态参数"
                }
            } else {
                if (this.paramsForm.attr_id > 0) {
                    return "修改静态属性"
                } else {
                    return "添加静态属性"
                }
            }
        }
    },
}
</script>

<style lang="less" scoped>
.cate-opt {
    margin-top: @default-margin;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>